<template>
  <el-cascader
    v-model="selectedOptions"
    :options="options"
    placeholder="选择地区"
    clearable
    class="region-selector"
    @change="handleChange"
  />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import regions from '@/assets/regions.json'

const options = ref([])
const selectedOptions = ref([])

const emit = defineEmits(['region-change'])

const handleChange = (value) => {
  // 发送最后选择的地区ID
  emit('region-change', value ? value[value.length - 1] : null)
}

//调用本地地区数据，获取后端数据库对应的id
const loadOptions = () => {
  options.value = regions.map(province => ({
    value: province.id,
    label: province.name,
    children: province.cities.map(city => ({
      value: city.id,
      label: city.name
    }))
  }))
}

onMounted(() => {
  try {
    loadOptions()
  } catch (error) {
    console.error('加载地区数据失败:', error)
    ElMessage.error('加载地区数据失败')
  }
})
</script>

<style scoped>
.region-selector {
  width: 300px;
}
</style>